package soup;

import java.io.IOException;
import java.io.InputStream;

import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;

import static org.lwjgl.opengl.GL11.*;
/**
 * Wraps an OpenGL texture. Lets you render it at a position and rotation
 * @author Sam
 */
public class Sprite {
	/**
	 * Dimensions of Sprite
	 */
	float w, h; //in modelview space
	float tw, th; //in texture space
	/**
	 * Texture that we draw from
	 */
	Texture tex;
	
	public Sprite(String format, InputStream in) throws IOException {
		tex = TextureLoader.getTexture(format, in);
		w = tex.getImageWidth(); h = tex.getImageHeight();
		tw = w/tex.getTextureWidth(); th = h/tex.getTextureHeight();
	}
	
	public void render(float x, float y) {
		tex.bind();
		float w_2 = w/2, h_2 = h/2;
		glBegin(GL_QUADS);
		{
			glTexCoord2f(0,0);
			glVertex2f(x-w_2,y-h_2);
			glTexCoord2f(tw,0);
			glVertex2f(x+w_2,y-h_2);
			glTexCoord2f(tw,th);
			glVertex2f(x+w_2,y+h_2);
			glTexCoord2f(0,th);
			glVertex2f(x-w_2,y+h_2);
		}
		glEnd();
	}
	
	public void render(float x, float y, float r) {
		glPushMatrix();
		tex.bind();
		glTranslatef(x, y, 0);
		glRotatef(r, 0, 0, 1);
		float w_2 = w/2, h_2 = h/2;
		glBegin(GL_QUADS);
		{
			glTexCoord2f(0,0);
			glVertex2f(-w_2,-h_2);
			glTexCoord2f(tw,0);
			glVertex2f(w_2,-h_2);
			glTexCoord2f(tw,th);
			glVertex2f(w_2,h_2);
			glTexCoord2f(0,th);
			glVertex2f(-w_2,h_2);
		}
		glEnd();
		glPopMatrix();
	}
}